package logic

import (
	"context"
	"fmt"
	pkg "pkg/Validate"
	"user_srv/internal/svc"
	"user_srv/models"
	"user_srv/user_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type ValiDateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewValiDateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ValiDateLogic {
	return &ValiDateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ValiDateLogic) ValiDate(in *user_srv.ValiDateRequest) (*user_srv.ValiDateResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("id_card = ?", in.UserId).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("信息已被使用")
	}
	if models.DB.Where("id = ?", in.UserId).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不可用")
	}
	date := pkg.ValiDate(in.CodeId, in.RealName)
	if date.ErrorCode != 0 {
		return nil, fmt.Errorf("实名信息调用权限不足，请联系管理员")
	}
	if !date.Result.Isok {
		return nil, fmt.Errorf("实名失败")
	}
	user.IdCard = in.CodeId
	user.RealName = in.RealName
	if models.DB.Updates(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &user_srv.ValiDateResponse{}, nil
}
